package todolist.entity;

import java.util.Properties;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

//nus.st1112.cs2103@gmail.com
//ST1112CS2103

public class EmailEntity {

	private String _strUserName;
	private String _strPassword;
	private Properties _pptEmail;
	private Session _ssnEmail;

	public EmailEntity(String pstrUserName, String pstrPassword) {
		_strUserName = pstrUserName;
		_strPassword = pstrPassword;
		_pptEmail = new Properties();
		initEmailProperties();
		initEmailSession();
	}

	private void initEmailProperties() {
		_pptEmail.put("mail.smtp.auth", "true");
		_pptEmail.put("mail.smtp.starttls.enable", "true");
		_pptEmail.put("mail.smtp.host", "smtp.gmail.com");
		_pptEmail.put("mail.smtp.port", "587");
	}
	
	private void initEmailSession(){
		_ssnEmail = Session.getInstance(_pptEmail,
				new javax.mail.Authenticator() {
					protected PasswordAuthentication getPasswordAuthentication() {
						return new PasswordAuthentication(_strUserName, _strPassword);
					}
				});
	}

	public String sendEmail(String pstrRecipientEmail, String pstrEmailSubject, String pstrEmailContent) {
		try {
			Message message = new MimeMessage(_ssnEmail);
			message.setFrom(new InternetAddress(_strUserName)); // from
			message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(pstrRecipientEmail)); // to
			message.setSubject(pstrEmailSubject);
			message.setText(pstrEmailContent);

			Transport.send(message);

			return "Daily tasks overview email sent successfully.";

		} catch (MessagingException e) {
			//throw new RuntimeException(e);
			return "Fail to send daily tasks overview email.";
		}
	}
}
